/**
 * Created by xiongisxiong on 2018/5/30
 * 音频播放器
 */
import React, { PureComponent } from 'react' 
import Video from 'react-native-video'

import { MUSIC_URL } from '../api'
import { tools } from '../utils'

import { connect } from 'react-redux'
import { setPlaySong } from '../redux/actions'

  class Player extends PureComponent {
    state = {
      musicUrl: ''
    }
    componentWillReceiveProps(nextProps) {
      const { currentPlayId, currentPlay } = this.props;
      const nextPlayId = nextProps.currentPlayId;
      const nextCurrentPlay = nextProps.currentPlay;
      console.log('Player中props改变后的nextCurrentPlay：', nextCurrentPlay);
      if (currentPlayId !== nextPlayId) { // 获取新的播放地址
        this.getMusicUrl(nextPlayId)
      }
      if (currentPlay.ff !== nextCurrentPlay.ff) { // 快进快退操作
        this.player.seek(nextCurrentPlay.ff)
      }
    }
    /** 获取新的播放地址 函数 */
    getMusicUrl = id => {
      try {
        (
          async () => {
            const res = await fetch(MUSIC_URL + id);
            const json = await res.json();
            console.log('新的播放地址：', json.data[0].url)
            this.setState({
              musicUrl: json.data[0].url
            })
          }
        )()
      } catch (err) {
        alert(err)
      }
    }
    loadStart = () => {}
    setDuration = (obj) => {
      // 音频加载后的信息，obj为该MP3的对象信息，包括currentTime: 0, duration: 193.646
      console.log('setDuration:',obj);
      this.props.dispatch(setPlaySong({
        duration: obj.duration, // 总秒数
        playTime: tools.transTime(obj.duration), // 将总秒数转化为了总时间类型
        playing: true
      }))
    }
    setTime = (time) => {
      const { duration } = this.props.currentPlay;
      this.props.dispatch(setPlaySong({
        currentTime: tools.transTime(time.currentTime), 
        sliderProgress: time.currentTime / duration
      }))
    }
    onEnd = () => {}
    videoError = () => {}
    onBuffer = () => {}
    onTimedMetadata = () => {}
    render() {
      const { musicUrl } = this.state;
      const { currentPlay } = this.props;
      return (
        musicUrl ? (
          <Video 
              source={{uri: musicUrl}} // Can be a URL or a local file.
              ref={(ref) => {this.player = ref}} // Store reference
              rate={1.0} // 0 is 暂停, 1 is normal. 安卓
              volum={1.0} // 0 is 完全静音, 1 is normal.
              muted={false} // 完全静音
              paused={!currentPlay.playing} // Pauses playback entirely.
              resizeMode='cover' // 以纵横比填充整个屏幕。  安卓
              repeat={true} // 永远重复。
              playInBackground // 当应用程序输入背景音频时，音频继续播放。
              playWhenInactive={false} // [iOS]当显示控制或通知中心时，视频继续播放。
              progressUpdateInterval={250.0}  // [iOS] Interval to fire onProgress（默认为 〜250ms ）
              ignoreSilentSwitch={'ignore'} // [iOS] ignore | 服从 - 当'忽略'时，音频仍然会播放与iOS硬静音开关设置为静音。当“服从”时，音频将切换开关。当未指定时，将照常继承音频设置。
              onLoadStart={this.loadStart} // 视频开始加载时的回调
              onLoad={this.setDuration} // 视频加载时的回调
              onProgress={this.setTime} // 每250毫秒〜与currentTime的回调
              onEnd={this.onEnd} // 播放完成时的回调
              onError={this.videoError} // 当视频无法加载执行的回调
              onBuffer={this.onBuffer}  // 视频正在缓冲时回调
              onTimedMetadata={this.onTimedMetadata} // 当流接收到一些元数据的回调
              style={{width: 0, height: 0}}
          />
        ) : null
      )
    }
    
  } 

  const mapStateToProps = ({currentPlay}) => ({
    currentPlayId: currentPlay.id,
    currentPlay
  });

export default connect(mapStateToProps)(Player);